<?php
  require (DIR_LIBS . 'Smarty/' . SMARTY_VERSION .   '/Smarty.class.php');
  class iJTemplate extends Smarty {
    
    /*private final ENABLE  = 'enable';
    private final DISABLE = 'disable';  */

    public function __construct() {
      parent::__construct();
      $this->template_dir = DIR_TEMPLATES;
      $this->compile_dir  = DIR_SMARTY_COMPILE;
      $this->cache_dir = "/home/news.loc/www/smarty/cache/";
     // $this->config_dir = "/home/news.loc/www/smarty/configs/
      
    }
    

    public function render() {   
      $iJDataBase =  iJFactory::singleton('iJDataBase');
      
      $this->loadConfigTokens();
    
      $keyword = trim($_GET['keyword'], '/');
      if(empty($keyword)) {
        $keyword = 'index';
      } 
      
      $iJAdmin = iJFactory::singleton('iJAdmin');
 
      if($keyword == 'admin') {
        if(iJAdmin::isAdminLogin()) {
             iJRedirect(iJHrefLink::linkToLocalPage('admin_login')); 
        } else {
             iJRedirect(iJHrefLink::linkToLocalPage(ADMIN_START_PAGE));
        }
      }
     
      $redirect404 = false;
       
      $Qpage = $iJDataBase->query('SELECT 
                                    P.id, 
                                    def.value as title,
                                    P.isAdminPage, 
                                    P.keyword,
                                    P.header,
                                    P.cleft,
                                    P.cright,
                                    P.content,
                                    P.footer
                                  FROM :table_pages AS P
                                      :lang_join');
      $Qpage->bindTable(':table_pages', TABLE_PAGES);
      
      $Qpage->bindLaguageDefinitions(':lang_join', TABLE_PAGES, 'P');
      
      $Qpage->appendQuery('AND (P.url like :url)');
      $Qpage->bindValue(':url', $keyword); 
      $Qpage->execute();
      if($Qpage->next()) {
        $idPage         = $Qpage->value('id');
        $pageKeyword    = $Qpage->value('keyword');
        $isAdminPage    = $Qpage->value('isAdminPage');
        $title          = $Qpage->value('title');
        
        $pageInfo['header']     = $Qpage->value('header');
        $pageInfo['left']       = $Qpage->value('cleft');
        $pageInfo['right']      = $Qpage->value('cright');
        $pageInfo['content']    = $Qpage->value('content');
        $pageInfo['footer']     = $Qpage->value('footer');
        
        $this->assign('page_title', $title);
        $iJAdmin = iJFactory::singleton('iJAdmin');
        if($isAdminPage == 1) {
            if(!$iJAdmin->isAdminLogin() && $pageKeyword != 'admin_login') {
                iJRedirect(iJHrefLink::linkToLocalPage('admin_login'));
            }
            $templateFolder = DIR_BACKEND;
        } else {
            $templateFolder = DIR_FRONTEND;
        }
        
        $Qpage = $iJDataBase->query('SELECT
                                      bp.place,
                                      b.id,
                                      b.js,
                                      b.css,
                                      b.code,
                                      b.template,
                                      b.language,
                                      b.isAdmin
                                    FROM :table_blocks_to_pages AS bp
                                      LEFT JOIN :table_blocks AS b
                                        ON bp.idBlock = b.id
                                    WHERE bp.idPage = :idPage');
                                    
        $Qpage->bindTable(':table_blocks_to_pages', TABLE_BLOCKS_TO_PAGES);
        $Qpage->bindTable(':table_blocks',          TABLE_BLOCKS);
        
        $Qpage->bindValue(':idPage', $idPage, 'int');
        $Qpage->execute();
        
        $jsFiles  = array();
        $cssFiles = array();
        $block    = array();
        
        
        foreach($pageInfo as $container => $state) {
          if($state != 'disable') {
            $block[$container] = '';
          }
        }
        
  
         
        while($Qpage->next()) {

           $blockInf = $Qpage->toArray();
           if($blockInf['isAdmin'] == 1) {
             $templateFolder = DIR_BACKEND;
           } else {
             $templateFolder = DIR_FRONTEND;
           }
           if(!empty($blockInf['js'])) {
                $jsFiles[$blockInf['id']]  =  $blockInf['js'];
           }
           
           if(!empty($blockInf['css'])) {
                $cssFiles[$blockInf['id']]  =  $blockInf['css'];
           }
           
           if(!empty($blockInf['code'])) {
             $blockClass =  iJFactory::singleton($blockInf['code']);
             if(!is_null($blockClass)) {
               $this->loadTokens($blockClass->execute()); 
             } else {
               iJDebug::setError('Class ' . $blockInf['code'] . ' not found. '  . $blockInf['template']);
             }
           }
           $this->loadLanguageTockens($blockInf['language']);
              
           $plase  = strtolower($blockInf['place']);
           
           if(isset($pageInfo[$plase]) && $pageInfo[$plase] == 'disable' || !isset($block[$plase])) {
             iJDebug::setWarning('Page contains blocks inside unvisible container');
           } else {
             $block[$plase] = $block[$plase]  . $this->fetch($templateFolder . '/' . $blockInf['template']);            
           }
        }
        
        $this->loadTokens(iJMessages::getMessage());
       
        $xData = $this->fetch($templateFolder . '/' . 'Messages.tpl');
        $this->assign('xData', $xData);
        $this->assign('css',   $cssFiles);
        $this->assign('js',    $jsFiles);
        
        
        
        /* addind debug panel (admins only) */
        if(iJAdmin::isAdminLogin() && ENABLE_DEBUG_PANEL) {
          $this->loadLanguageTockens('debug.xml');  
          $this->assign('info', iJDebug::getDebugInfo());
          if(isset($pageInfo['left']) && $pageInfo['left'] == 'disable') {
            } else {
              $block['left']     = $block['left']  . $this->fetch(DIR_BACKEND . '/' . 'debug.tpl'); 
          }
        }
        
        $this->assign('block', $block);
        
        header( "Content-Type: text/html; charset=UTF-8" );
        if($isAdminPage == 1) {
            $this->display('backend/index.tpl');
        } else {
            $this->display('frontend/index.tpl');
        }
        
                                    
        
      } else {
      
        iJRedirect(iJHrefLink::linkToLocalPage('404'));
        die();
        
        $redirect404 = true;
      }
      
    }
    
    public function loadConfigTokens() {
        
      $this->assign('BACKEND_JS',      BACKEND_JS);
      $this->assign('BACKEND_CSS',     BACKEND_CSS);
      $this->assign('BACKEND_IMAGES',  BACKEND_IMAGES);
      
      $this->assign('FRONTEND_JS',     FRONTEND_JS);
      $this->assign('FRONTEND_CSS',    FRONTEND_CSS);
      $this->assign('FRONTEND_FLASH',  FRONTEND_FLASH);
      $this->assign('FRONTEND_IMAGES', FRONTEND_IMAGES);
      
      $this->assign('EXTERNAL_JS',     EXTERNAL_JS);
      
      $this->assign('EXTERNAL_JS_RELATIVE',     EXTERNAL_JS_RELATIVE);
          
      $this->assign('VAR_FOLDER',      VAR_FOLDER);
      
      $this->assign('AJAX',            AJAX);
      
        
    }
    
    public function loadTokens($arrayTokens) {
        if(!is_Null($arrayTokens)) {
           foreach($arrayTokens as $name => $value) {
             $this->assign($name, $value);
           } 
        } 
        
    }
    
    public function  loadLanguageTockens($blockLanguage) {
        if(!empty($blockLanguage)) {
            $iJLanguages = iJFactory::singleton('iJLanguages');
            $lang = iJEngineXML::getArrayFromXMLFile(DIR_BACKEND_LANGUAGES . $iJLanguages->getLangCode() . '/' . $blockLanguage);

            $blockLanguageTokens = array();
            if(empty($lang['language']['definition'])) {
                return;
            }
            if(isset($lang['language']['definition']['key'])) {
              $def = $lang['language']['definition'];
              unset($lang['language']['definition']);
              $lang['language']['definition'][0] = $def;
            }
          
            foreach($lang['language']['definition'] as $definition) {
                $blockLanguageTokens[$definition['key']]  = $definition['value'];
            }
            
            $blockLanguageTokens = array_merge($blockLanguageTokens, $iJLanguages->getDefaultTokens());
            $this->assign('lang', $blockLanguageTokens);
            
        }
        
        
        
    }



  }
 ?>